/**
 *
 * 事件总线
 *
 */
class EventBus {
	
    private static _eventHandlers: Object = {};
    
    private static _getRandId(): string {
        return new Date().getTime().toString() + Math.floor(Math.random() * 100000);
    } 
    
    public static on(eventType: string,handler: Function,context?: any): string {
        var id: string = EventBus._getRandId();
        EventBus._eventHandlers[eventType] || (EventBus._eventHandlers[eventType] = {});
        EventBus._eventHandlers[eventType][id] = {};
        EventBus._eventHandlers[eventType][id].cbk = handler;
        EventBus._eventHandlers[eventType][id].ctx = context;
        return id;
    }
    
    public static one(eventType: string,handler: Function,context?: any): string {
        var id: string = EventBus.on(eventType,function(data?: any) {
            handler.call(context, data);
            EventBus.off(eventType,id);
        }, context);
        return id;
    }
    
    public static off(eventType: string,id: string): void {
        if(EventBus._eventHandlers[eventType]) {
            delete EventBus._eventHandlers[eventType][id];
        }
    }
    
    public static trigger(eventType: string,data?: any): void {
        if(EventBus._eventHandlers[eventType]) {
            var i: string;
            for(i in EventBus._eventHandlers[eventType]) {
                EventBus._eventHandlers[eventType][i].cbk
                    .call(EventBus._eventHandlers[eventType][i].ctx,data);
            }
        }
    }
}
